//
//  DeviceInfo.m
//  SLRequest
//
//  Created by 虞嘉伟 on 2025/3/11.
//


#import "DeviceInfo.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <mach/mach.h>
#import <sys/utsname.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <Reachability/Reachability.h>
#import "WiFiInfo.h"
#import "MemoryInfo.h"
#import "DiskInfo.h"

@implementation DeviceInfo

+ (NSDictionary *)deviceInfo {
    NSString *principal = @"ios"; // 系统类型
    NSString *pinnacle = [[UIDevice currentDevice] systemVersion]; // 系统版本
    NSTimeInterval lastLoginTime = [NSUserDefaults.standardUserDefaults doubleForKey:@"lastLoginTime"];
    // 包名
    NSString *tower = [[NSBundle mainBundle] bundleIdentifier];
    //电池信息
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    float crossed = [[UIDevice currentDevice] batteryLevel] * 100; // 电池百分比
    int adventures = [UIDevice currentDevice].batteryState == UIDeviceBatteryStateCharging ? 1 : 0; // 是否充电
    // 设备标识和网络信息
    NSString *lonely = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; // IDFV
    NSString *cold = [RequestCommonParameter idfa]; //[[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString; // IDFA（需要 AdSupport 框架）
    NSString *visiting = WiFiInfo.shared.bssid ?: @""; // MAC 地址（iOS 无法直接获取，通常返回固定值）
    NSTimeInterval commended = [[NSDate date] timeIntervalSince1970] * 1000; // 当前时间戳
    int praise = 0; // 是否使用代理（需要额外检测）
    int examinations = 0; // 是否使用 VPN（需要额外检测）
    int notwithstanding = 0; // 是否越狱（需要额外检测）
    int teachers = 0; // 是否是模拟器（需要额外检测）
    NSString *certificate = [[NSLocale preferredLanguages] firstObject]; // 设备语言
    NSString *subjects = [CTTelephonyNetworkInfo new].subscriberCellularProvider.carrierName; // 网络运营商名称
    NSString *deserve = [self getNetworkType]; // @"WIFI"; // 网络类型（需要额外检测）
    NSString *lest = [NSTimeZone localTimeZone].name; // 时区
    NSTimeInterval stupid = [NSProcessInfo processInfo].systemUptime * 1000; // 设备启动毫秒数
    // 硬件信息
    NSString *divinity = @"iPhone"; // 设备品牌
    int feared = [UIScreen mainScreen].bounds.size.height; // 设备高度
    int overpowered = [UIScreen mainScreen].bounds.size.width; // 设备宽度
    NSString *mathematics = [[UIDevice currentDevice] name]; // 设备名称
    NSString *geography = [[UIDevice currentDevice] model]; // 设备型号
    NSString *oindicd = [self getDeviceModelIdentifier]; //@"iphone12,1"; // 原始设备型号（需要额外处理）
    NSString *wave = [self physical] ?: @""; //@"5.5"; // 物理尺寸（需要额外处理）
    NSString *floundered = [[UIDevice currentDevice] systemVersion]; // 系统版本
    // 网络模块
    NSString *confined = [self getLocalIPAddress]; // @"10.0.226.79"; // 内网 IP（需要额外处理）
    NSArray *bird = @[
        @{
            @"veins": WiFiInfo.shared.ssid ?: @"", //@"Shu_Xing", // 当前 WiFi 名称
            @"chamber": WiFiInfo.shared.bssid ?: @"", //@"68:D7:9A:7B:71:36", // 当前 WiFi BSSID
            @"visiting": WiFiInfo.shared.bssid ?: @"", //@"68:D7:9A:7B:71:36", // 当前 WiFi MAC
            @"boarded": WiFiInfo.shared.ssid ?: @"", //@"Shu_Xing" // 当前 WiFi SSID
        }
    ]; // WiFi 列表（需要额外处理）
    NSDictionary *rolling = @{
        @"veins": WiFiInfo.shared.ssid ?: @"", //@"Shu_Xing", // 当前 WiFi 名称
        @"chamber": WiFiInfo.shared.bssid ?: @"", //@"68:D7:9A:7B:71:36", // 当前 WiFi BSSID
        @"visiting": WiFiInfo.shared.bssid ?: @"", //@"68:D7:9A:7B:71:36", // 当前 WiFi MAC
        @"boarded": WiFiInfo.shared.ssid ?: @"", //@"Shu_Xing" // 当前 WiFi SSID
    };
    int resounded = bird.count > 0 ? 1 : 0; // WiFi 列表是否有数据
    /// 存储模块
    NSNumber *remote = @([DiskInfo freeDisk]); // 未使用存储大小
    NSNumber *furnished = @([DiskInfo totalDisk]); // 总存储大小
    
    // 内存信息
    NSNumber *maid = @([MemoryInfo totalMemory]); // 总内存大小
    NSNumber *rehearsal = @([MemoryInfo freeMemory]); // 未使用内存大小
    
    NSDictionary *dict = @{
        @"principal": principal ?: @"",
        @"pinnacle": pinnacle ?: @"",
        @"windows": @(lastLoginTime) ?: @"",
        @"tower": tower ?: @"",
        @"lofty": @{
            @"crossed": @(crossed) ?: @"",
            @"adventures": @(adventures) ?: @"",
        },
        @"seek": @{
            @"lonely": lonely ?: @"",
            @"cold": cold ?: @"",
            @"visiting": visiting ?: @"",
            @"commended": @(commended) ?: @"",
            @"praise": @(praise) ?: @"",
            @"examinations": @(examinations) ?: @"",
            @"notwithstanding": @(notwithstanding) ?: @"",
            @"teachers": @(teachers) ?: @"",
            @"certificate": certificate ?: @"",
            @"subjects": subjects ?: @"",
            @"deserve": deserve ?: @"",
            @"lest": lest ?: @"",
            @"stupid": @(stupid) ?: @""
        },
        @"incorrectly": @{
            @"unconditionally": @"",
            @"divinity": divinity ?: @"",
            @"exception": @"",
            @"feared": @(feared) ?: @"",
            @"overpowered": @(overpowered) ?: @"",
            @"mathematics": mathematics ?: @"",
            @"geography": geography ?: @"",
            @"oindicd": oindicd ?: @"",
            @"wave": wave ?: @"",
            @"floundered": floundered ?: @"",
        },
        @"cage": @{
            @"confined": confined ?: @"",
            @"bird": bird ?: @"",
            @"rolling": rolling ?: @"",
            @"resounded": @(resounded)
        },
        @"coast": @{
            @"remote": remote ?: @"",
            @"furnished": furnished ?: @"",
            @"maid": maid ?: @"",
            @"rehearsal": rehearsal ?: @"",
        }
    };
    return dict;
}

+ (NSString *)getNetworkType {
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reachability currentReachabilityStatus];
    
    switch (status) {
        case NotReachable:
            return @"No Network";
        case ReachableViaWiFi:
            return @"Wi-Fi";
        case ReachableViaWWAN:
            return @"Cellular";
        default:
            return @"Unknown";
    }
}

+ (NSString *)getDeviceModelIdentifier {
    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

+ (NSString *)getLocalIPAddress {
    NSString *localIP = nil;
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    
    // 获取网络接口列表
    if (getifaddrs(&interfaces) == 0) {
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            // 检查接口是否为IPv4地址
            if (temp_addr->ifa_addr->sa_family == AF_INET) {
                // 检查接口名称是否为Wi-Fi（en0）或蜂窝网络（pdp_ip0）
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"] ||
                    [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"pdp_ip0"]) {
                    // 转换为IP地址字符串
                    localIP = [NSString stringWithUTF8String:
                               inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    break;
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // 释放内存
    freeifaddrs(interfaces);
    return localIP;
}

+ (NSString *)physical {
    CGFloat std = sqrt(414*414 + 896*896); //987.02178294098451
    CGSize size = UIScreen.mainScreen.bounds.size;
    CGFloat diagonal = sqrt(size.width*size.width + size.height*size.height);
    CGFloat x = diagonal/std*6.1;
    return [NSString stringWithFormat:@"%.1f", x];
}
@end
